<template>
	<xn-form-container
		:title="formData.templateId ? '编辑导入模版' : '增加导入模版'"
		:width="700"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="模版编码：" name="templateCode">
				<a-input v-model:value="formData.templateCode" :maxlength="30" placeholder="请输入模版编码" allow-clear />
			</a-form-item>
			<a-form-item label="模版名称：" name="dataName">
				<a-input v-model:value="formData.dataName" :maxlength="30" placeholder="请输入模版名称" allow-clear />
			</a-form-item>
			<a-form-item label="模版地址：" name="dataUrl">
				<UploadFile ref="dataUrlUploadRef" :limitImage="1"></UploadFile>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="dataMgrForm">
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import excelTemplateApi from '@/api/biz/excelTemplateApi'
	import UploadFile from '@/components/FileUpload/index.vue'

	// 抽屉状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	const dataUrlUploadRef = ref()
	// 表单数据
	const formData = ref({})
	const submitLoading = ref(false)

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		if (record) {
			let recordData = cloneDeep(record)
			formData.value = Object.assign({}, recordData)
		}
		nextTick(() => {
			if (record && record.dataUrl) {
				dataUrlUploadRef.value.initFileList(record.dataUrl)
			}
		})
	}
	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		formData.value = {}
		visible.value = false
	}
	// 默认要校验的
	const formRules = {
		templateCode: [required('请输入模版编码')],
		dataName: [required('请输入模版名称')],
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			formData.value.dataUrl = dataUrlUploadRef.value.buildUrl()
			submitLoading.value = true
			const formDataParam = cloneDeep(formData.value)
			excelTemplateApi
				.excelTemplateSubmitForm(formDataParam, formDataParam.templateId)
				.then(() => {
					onClose()
					emit('successful')
				})
				.finally(() => {
					submitLoading.value = false
				})
		})
	}
	// 抛出函数
	defineExpose({
		onOpen
	})
</script>
